<template>
  <view v-show="!isLoading" class="container">
	  <u-toast ref="uToast" />
	  <!-- 支付弹出层 -->
	  <u-popup safe-area-inset-bottom z-index="11000" :mask-custom-style="style" v-model="addressShowPo" height ='500' :mask-close-able='false' mode="bottom" closeable  border-radius="14">
	  		<view class="popup_tan">
	  			<view class="" style="height: 80rpx;">
	  				
	  			</view>
				<view class="address_select">
					
					<view class="address_select_item" v-for="(item,index) in addressList"  @click="selectAddress(item)">
						<view class="between">
							<view class="">
								{{item.receiverPerson}}
							</view>
							<view class="">
								{{item.receiverPhone}}
							</view>
						</view>
						<view class="">
							{{item.receiverArea}}{{ item.receiverAddr }}
						</view>
					</view>
				</view>
	  				
	  				
	  				
	  		</view>	
	  		
	  </u-popup>
	  <u-popup safe-area-inset-bottom :mask-custom-style="style" v-model="zfShow" height ='430' :mask-close-able='false' mode="bottom" closeable  border-radius="14">
	  		<view class="popup_tan">
	  			<view class="" style="height: 80rpx;">
	  				
	  			</view>
				<view class="address_select">
					<view class="" v-if='address==null'  @click="addressShow()">
						请选择地址
					</view>
					<view class="" v-else @click="addressShow()">
						<view class="between">
							<view class="">
								{{address.receiverPerson}}
							</view>
							<view class="">
								{{address.receiverPhone}}
							</view>
						</view>
						<view class="">
							{{address.receiverArea}}{{ address.receiverAddr }}
						</view>
					</view>
				</view>
				<view class="between" style="margin-top: 20rpx;">
					<view class="">
						数量:
					</view>
					<u-number-box  v-model="numValue" :min="1" :max="50"></u-number-box>
				</view>
				<view class="" style="margin-top: 20rpx;">
					<u-button style="" type="primary" @click="payNow()">购买</u-button>
				</view>
				
	  		</view>	
				
				 
				 <!-- <u-button type="primary" size="large" >购买</u-button> -->
	  		</u-popup>
	  <!-- <u-popup :show="zfShow" :round="10" mode="bottom"  closeable @open="open">
	  	<view style="height: 1200rpx;">
	          <u-button type="primary" size="large" text="购买"></u-button>
	  	</view>
	  </u-popup> -->
    <!-- 商品图片轮播 -->
    <!-- <SlideImage v-if="!isLoading" :video="goods.video" :videoCover="goods.videoCover" :images="goods.goodsImg" /> -->
	<view class="">
		<image :src="goods.goodsImg" mode="widthFix" style="width: 100%;"></image>
	</view>
    <!-- 商品信息 -->
    <view  class="goods-info m-top20">
      <!-- 价格、销量 -->
      <view class="info-item info-item__top dis-flex flex-x-between flex-y-end">
        <view class="block-left dis-flex flex-y-center">
          <!-- 商品售价 -->
          <text class="floor-price__samll">￥</text>
          <text class="floor-price">{{ goods.goodsCurrentPrice }}</text>
          <!-- 会员价标签 -->
          <!-- <view v-if="goods.is_user_grade" class="user-grade">
            <text>会员价</text>
          </view> -->
          <!-- 划线价 -->
          <text v-if="goods.goodsOriginalPrice > 0" class="original-price">￥{{ goods.goodsOriginalPrice }}</text>
        </view>
        <view class="block-right dis-flex">
          <!-- 销量 -->
          <view class="goods-sales">
            <text>剩余{{ goods.inventoryNum }}件</text>
          </view>
        </view>
      </view>
      <!-- 标题、分享 -->
      <view class="info-item info-item__name dis-flex flex-y-center">
        <view class="goods-name flex-box">
          <text class="twoline-hide">{{ goods.goodsName }}</text>
        </view>
        <!-- #ifdef MP-WEIXIN -->
        <view class="goods-share__line"></view>
       <!-- <view class="goods-share">
          <button class="share-btn dis-flex flex-dir-column" open-type="share">
            <text class="share__icon iconfont icon-fenxiang"></text>
            <text class="f-24">分享</text>
          </button>
        </view> -->
        <!-- #endif -->
      </view>
      <!-- 商品卖点 -->
      <view v-if="goods.selling_point" class="info-item info-item_selling-point">
        <text>{{ goods.selling_point }}</text>
      </view>
    </view>

    <!-- 选择商品规格 -->
    <view v-if="goods.spec_type == 20" class="goods-choice m-top20 b-f" @click="onShowSkuPopup(1)">
      <view class="spec-list">
        <view class="flex-box">
          <text class="col-8">选择：</text>
          <text class="spec-name" v-for="(item, index) in goods.specList" :key="index">{{ item.spec_name }}</text>
        </view>
        <view class="f-26 col-9 t-r">
          <text class="iconfont icon-arrow-right"></text>
        </view>
      </view>
    </view>

    <!-- 商品服务 -->
    <Service v-if="!isLoading" :goods-id="goodsId" />

    <!-- 商品SKU弹窗 -->
    <SkuPopup v-if="!isLoading" v-model="showSkuPopup" :skuMode="skuMode" :goods="goods" @addCart="onAddCart" />

    <!-- 商品评价 -->
    <Comment v-if="!isLoading" :goods-id="goodsId" :limit="2" />

    <!-- 商品描述 -->
    <view v-if="!isLoading" class="goods-content m-top20">
      <view class="item-title b-f">
        <text>商品描述</text>
      </view>
      <block v-if="goods.goodsIntroduce != ''">
        <view class="goods-content__detail b-f">
          <mp-html :content="goods.goodsIntroduce" />
        </view>
      </block>
      <empty v-else tips="亲，暂无商品描述" />
    </view>
	<view v-if="goods.izKey" class="goods-content m-top20">
	  <view class="item-title b-f">
	    <text>赠送抽奖奖池</text>
	  </view>
	  <view class="">
	  	<image :src="jackpotDetail.jackpotUrl" mode="widthFix" style="width: 100%;"></image>
	  </view>
	  <!-- <block v-if="goods.goodsIntroduce != ''">
	    <view class="goods-content__detail b-f">
	      <mp-html :content="goods.goodsIntroduce" />
	    </view>
	  </block> -->
	  <!-- <empty v-else tips="亲，暂无商品描述" /> -->
	</view>

    <!-- 底部选项卡 -->
    <view class="footer-fixed">
      <view class="footer-container">
        <!-- 导航图标 -->
        <view class="foo-item-fast">
          <!-- 首页 -->
          <view class="fast-item fast-item--home" @click="onTargetHome">
            <view class="fast-icon">
              <text class="iconfont icon-shouye"></text>
            </view>
            <view class="fast-text">
              <text>首页</text>
            </view>
          </view>
          <!-- 客服 (仅微信小程序端显示) -->
          <!-- #ifdef MP-WEIXIN -->
          <!-- <button class="btn-normal" open-type="contact">
            <view class="fast-item">
              <view class="fast-icon">
                <text class="iconfont icon-kefu1"></text>
              </view>
              <view class="fast-text">
                <text>客服</text>
              </view>
            </view>
          </button> -->
          <!-- #endif -->
          <!-- 购物车 -->
          <!-- <view class="fast-item fast-item--cart" @click="onTargetCart">
            <view v-if="cartTotal > 0" class="fast-badge fast-badge--fixed">{{ cartTotal > 99 ? '99+' : cartTotal }}
            </view>
            <view class="fast-icon">
              <text class="iconfont icon-gouwuche"></text>
            </view>
            <view class="fast-text">
              <text>购物车</text>
            </view>
          </view> -->
        </view>
        <!-- 操作按钮 -->
        <view class="foo-item-btn">
          <view class="btn-wrapper">
            <!-- <view class="btn-item btn-item-deputy" @click="onShowSkuPopup(2)">
              <text>加入购物车</text>
            </view> -->
            <view class="btn-item btn-item-main" @click="clickZf()">
              <text>立即购买</text>
            </view>
          </view>
        </view>
      </view>
    </view>
	
    <!-- 快捷导航 -->
    <!-- <shortcut bottom="120rpx" /> -->

  </view>
</template>

<script>
  import * as GoodsApi from '@/api/goods'
  import * as CartApi from '@/api/cart'
    import {listByUserId} from '@/tyapi/address.js'
  // import Shortcut from '@/components/shortcut'
  import SlideImage from './components/SlideImage'
  import SkuPopup from './components/SkuPopup'
  import Comment from './components/Comment'
  import Service from './components/Service'
  import{goodsDetail,placeAnOrder,jackpotDetail,wxPay,checkOrderStatus} from '@/tyapi/address.js'

  export default {
    components: {
      // Shortcut,
      SlideImage,
      SkuPopup,
      Comment,
      Service
    },
    data() {
      return {
		  addressId:'',
		  addressShowPo:false,
		  numValue:1,
		  style:{background: 'rgba(0, 0, 0, 0.5)'},
		  address:null,
		  zfShow:false,
		  jackpotDetail:{},
		  orderId:'',
		  goodsData:{},
        // 正在加载
        isLoading: true,
        // 当前商品ID
        goodsId: null,
        // 商品详情
        goods: {},
        // 购物车总数量
        cartTotal: 0,
		addressList:[],
        // 显示/隐藏SKU弹窗
        showSkuPopup: false,
        // 模式 1:都显示 2:只显示购物车 3:只显示立即购买
        skuMode: 1
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      // 记录商品ID
	  this.getAddressData()
      this.goodsId = options.goodsId
      // 加载页面数据
      this.onRefreshPage()
    },

    methods: {
		addressShow(){
			this.addressShowPo=true
		},
		// 选取地址
		selectAddress(address){
			this.address=address
			this.addressId=address.id
			this.addressShowPo=false
		},
		// 获取地址
		getAddressData() {
				listByUserId().then(res => {
					if(res.data.code == 200){
						this.addressList = res.data.data;
						
						
					}
				})
		},
		// 点击购买按钮
		clickZf(){
			 
			console.log("clickZf")
			this.zfShow=true
			console.log(this.zfShow)
			this.$refs['popup'].open('top')
		},
      // 刷新页面数据
      onRefreshPage() {
        const app = this
        app.isLoading = true
        Promise.all([app.getGoodsDetail(), app.getCartTotal()])
          .finally(() => app.isLoading = false)
      },
	  // 获取赠送奖池
	  getjackpotDetail(id){
		  jackpotDetail(id).then(res => {
		  	console.log(res.data)
		  	
		  	if(res.data.code == 200){
		  		this.jackpotDetail = res.data.data;
		  		
		  		
		  	}
		  })
	  },
      // 获取商品信息
      getGoodsDetail() {
        const app = this
		goodsDetail(app.goodsId).then(res => {
			console.log(res.data)
			this.goods = res.data.data;
			if(res.data.code == 200){
				if(res.data.data.izKey){
					this.getjackpotDetail(res.data.data.jackpotId)
				}
				if(res.data.msg == "0"){
					//没有获取userID
					uni.showToast({
						icon:"error",
						title:"请重新登录",
						duration:2000
					})
				}else if( res.data.msg == "操作成功"){
					console.log(res.data)
					this.goods = res.data.data;
				}
				
			}
		})
        // return new Promise((resolve, reject) => {
        //   GoodsApi.detail(app.goodsId)
        //     .then(result => {
        //       app.goods = result.data.detail
        //       resolve(result)
        //     })
        //     .catch(reject)
        // })
      },

      // 获取购物车总数量
      getCartTotal() {
        const app = this
        return new Promise((resolve, reject) => {
          CartApi.total()
            .then(result => {
              app.cartTotal = result.data.cartTotal
              resolve(result)
            })
            .catch(reject)
        })
      },

      // 更新购物车数量
      onAddCart(total) {
        this.cartTotal = total
      },
	payWxPay(id){
		wxPay(id).then(res => {
			console.log(res.data)
			// this.goods = res.data.data;
			if(res.data.code == 200){
				// this.orderId=res.data.data
				
				this.uniWxPay(res.data.data)
			}
		})
	},
	uniWxPay(data){
		const app = this
		uni.requestPayment({
		    provider: 'wxpay',
			// timeStamp: String(Date.now()),
			timeStamp: data.timeStamp,
			nonceStr: data.nonceStr,
			package: data.packageVal,
			signType: data.signType,
			paySign: data.paySign,
			success: function (res) {
				checkOrderStatus(app.orderId).then(res1 => {
					console.log(res1.data)
					uni.navigateTo({
						url: '/pages/order/index'
					});
					// this.goods = res.data.data;
					if(res1.data.code == 200){
						// this.orderId=res.data.data
						
					}
				})
				console.log('success:' + JSON.stringify(res));
			},
			fail: function (err) {
				console.log('fail:' + JSON.stringify(err));
			}
		});
	},
	
	payNow(){
		if(this.addressId==''){
			
							this.$refs.uToast.show({
								title: '请选择地址',
								type: 'success'
							})
						
		}else{
			
		
		var form = {
			goodsId:this.goodsId,
			goodsNumber:this.numValue.toString(),
			addressId:this.addressId,
			payType:"0",
		}
		placeAnOrder(form).then(res => {
			console.log(res.data)
			// this.goods = res.data.data;
			if(res.data.code == 200){
				this.orderId=res.data.data
				this.payWxPay(res.data.data)
				
			}
		})
		}
	},
      /**
       * 显示/隐藏SKU弹窗
       * @param {skuMode} 模式 1:都显示 2:只显示购物车 3:只显示立即购买
       */
      onShowSkuPopup(skuMode = 1) {
        this.skuMode = skuMode
        this.showSkuPopup = !this.showSkuPopup
      },

      // 跳转到首页
      onTargetHome(e) {
		  uni.navigateTo({
		  	url:'/pages/index/index'
		  })
      },

      // 跳转到购物车页
      onTargetCart() {
        this.$navTo('pages/cart/index')
      },

    },

    /**
     * 分享当前页面
     */
    onShareAppMessage() {
      const app = this
      // 构建页面参数
      const params = app.$getShareUrlParams({
        goodsId: app.goodsId,
      })
      return {
        title: app.goods.goods_name,
        path: `/pages/goods/detail?${params}`
      }
    },

    /**
     * 分享到朋友圈
     * 本接口为 Beta 版本，暂只在 Android 平台支持，详见分享到朋友圈 (Beta)
     * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
     */
    onShareTimeline() {
      const app = this
      // 构建页面参数
      const params = app.$getShareUrlParams({
        goodsId: app.goodsId,
      })
      return {
        title: app.goods.goods_name,
        path: `/pages/goods/detail?${params}`
      }
    }
  }
</script>

<style>
  page {
    background: #fafafa;
  }
</style>
<style lang="scss" scoped>
	.popup_tan{
		padding: 10rpx
	}
	.address_select{
		padding: 10rpx;
		background-color: #fff;
		border-radius: 10rpx;
		
	}
	.address_select_item{
		padding: 10rpx;
		border-bottom: 2rpx solid #ccc;
	}
  @import "./detail.scss";
</style>
